package com.it.service.impl;

import com.it.common.ErrorCode;
import com.it.model.LoginUserDTO;
import com.it.service.UserService;
import com.it.utils.Assert;
import com.it.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/7/19 7:56 下午
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public String login(LoginUserDTO user) {
        // 验证用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        Assert.notNull(authentication, ErrorCode.LOGIN_ERROR);

        // 将用户信息存入 redis
        //LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJWT(user.getUserName());
        return token;
    }
}
